<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="12">
            <a-form-model-item
              label="投料记录单号"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="feedingRecordCode"
            >
              <a-input v-model="model.feedingRecordCode" disabled placeholder=""></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="计划单号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="planCode">
              <a-input v-model="model.planCode" disabled placeholder=""></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="物料名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="materialName">
              <a-input v-model="model.materialName" disabled placeholder=""></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="规格型号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="materialSpec">
              <a-input v-model="model.materialSpec" disabled placeholder=""></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="包装班组" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="packageTeam">
              <a-select v-model="model.packageTeam" placeholder="请选择包装班组" style="width: 100%">
                <a-select-option v-for="item in packageTeamList" :key="item.id" :value="item.id">
                  {{ item.team }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="" :key="refKeys[0]" :forceRender="true">
        <a-row :gutter="20" style="margin-bottom: 5px" v-if="!formDisabled">
          <a-col :span="2">
            <a-button @click="handleAddMaterial" type="primary" icon="plus">新增物料</a-button>
          </a-col>
        </a-row>
        <j-vxe-table
          keep-source
          :ref="refKeys[0]"
          :loading="erpPackageFeedingDetailTable.loading"
          :columns="erpPackageFeedingDetailTable.columns"
          :dataSource="erpPackageFeedingDetailTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true" 
          :toolbarConfig="{ slot: ['prefix', 'suffix'], btn: ['remove', 'clearSelection'] }"
        />
      </a-tab-pane>
    </a-tabs>
    <!-- 该车间仓库下的物料列表 -->
  <material-list-modal ref="materialListModal" @ok="selectMaterial"/>
  </a-spin>
</template>

<script>
import { getAction, putAction } from '@/api/manage'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { getRefPromise, VALIDATE_FAILED } from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import { validateDuplicateValue } from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'
import MaterialListModal from '../../feedingbefore/modules/MaterialListModal.vue'

export default {
  name: 'ErpPackageFeedingForm',
  mixins: [JVxeTableModelMixin],
  components: {MaterialListModal},
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      model: {},
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 0,
      addRowBtn: false,
      validatorRules: {
        feedingRecordCode: [{ required: true, message: '投料记录单号不能为空', trigger: 'blur' }],
        packageTeam: [{ required: true, message: '包装班组不能为空', trigger: 'blur' }],
      },
      refKeys: ['erpPackageFeedingDetail'],
      tableKeys: ['erpPackageFeedingDetail'],
      activeKey: 'erpPackageFeedingDetail',
      // 包装投料明细
      erpPackageFeedingDetailTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '物料编码',
            key: 'materialCode',
            type: JVXETypes.normal,
            width: '200px',
            defaultValue: '',
          },
          {
            title: '物料名称',
            key: 'materialName',
            type: JVXETypes.normal,
            width: '200px',
            defaultValue: '',
          },
          {
            title: '规格型号',
            key: 'materialSpec',
            type: JVXETypes.normal,
            width: '200px',
            defaultValue: '',
          },
          {
            title: '主计量单位',
            key: 'meUnit',
            dictCode: 'ji_unit',
            type: JVXETypes.select,
            width: '200px',
            disabled: true,
            defaultValue: '',
          },
          {
            title: '主数量',
            key: 'meNum',
            type: JVXETypes.normal,
            width: '200px',
            defaultValue: '',
          },
          {
            title: '辅计量单位',
            key: 'auUnit',
            dictCode: 'zl_unit',
            type: JVXETypes.select,
            width: '200px',
            disabled: true,
            defaultValue: '',
          },
          {
            title: '辅数量',
            key: 'auNum',
            type: JVXETypes.normal,
            width: '200px',
            defaultValue: '',
          },
          {
            title: '批次号',
            key: 'batchNo',
            type: JVXETypes.normal,
            width: '200px',
            defaultValue: '',
          },
          {
            title: '物料批号',
            key: 'materialBatchNo',
            type: JVXETypes.normal,
            width: '200px',
            defaultValue: '',
          },
          {
            title: '库存数量',
            key: 'stockNum',
            type: JVXETypes.normal,
            width: '200px',
            defaultValue: '',
          },
          {
            title: '投料数量',
            key: 'feedingNum',
            type: JVXETypes.inputNumber,
            width: '200px',
            placeholder: '请输入${title}',
            validateRules: [{ required: true, message: '${title}不能为空' }],
            defaultValue: '',
            fixed: 'right',
          },
        ],
      },
      url: {
        add: '/feedingpackage/erpPackageFeeding/add',
        edit: '/feedingpackage/erpPackageFeeding/edit',
        queryById: '/feedingpackage/erpPackageFeeding/queryById',
        packageDetailList: '/packageprocessconfirmation/erpPackageProcessConfirmation/queryPackageDetailById',
        packageTeamList: '/packageteam/erpPackageTeam/list',
        erpPackageFeedingDetail: {
          list: '/feedingpackage/erpPackageFeeding/queryErpPackageFeedingDetailByMainId',
        },
      },
      packageTeamList: [],
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
    //新增功能的传值
    confirmationData: {
      type: Object,
      default: () => ({}),
      required: false,
    },
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {},
  methods: {
    add() {
      this.erpPackageFeedingDetailTable.dataSource = []
      this.getSequenceNum()
      // 执行自定义的addAfter逻辑
      if (typeof this.addAfter === 'function') this.addAfter()
      
      // 跳过原mixin中的自动添加行代码
      // 直接调用edit方法打开弹窗
      this.edit(this.model)
      
      // 执行自定义的addAfter逻辑
      if (typeof this.addAfter === 'function') this.addAfter(this.model)
    },
    // 重写编辑方法，确保不会添加行
    edit(record) {
      let packshopCode = record.packshopCode?record.packshopCode:this.confirmationData.packshopCode
      getAction(this.url.packageTeamList, {
        pageSize: 999,
        pageNo: 1,
        departCode: packshopCode,
      }).then((res) => {
        if (res.success) {
          this.packageTeamList = res.result.records
        }
      })
      if (typeof this.editAfter === 'function') this.editAfter(record)
      this.visible = true
      this.activeKey = this.refKeys[0]
      this.model = Object.assign({}, record)
      
      // 跳过原mixin中的自动添加行逻辑
      // 直接执行编辑后回调
      if (typeof this.editAfter === 'function') this.editAfter(this.model)
    },
    getSequenceNum() {
      let url = '/sys/fillRule/executeRuleByCode/package_feeding_code	'
      putAction(url, {}).then((res) => {
        // 执行成功，获取返回的值，并赋到页面上
        if (res.success) {
          this.model = {
            ...this.confirmationData,
            feedingRecordCode: res.result,
          }
        }
      })
    },
    loadPackageFeedingDetail() {
      getAction(this.url.packageDetailList, { order: this.model.orderCode, formula: this.model.formulaNumber })
        .then((res) => {
          if (res.success) {
            let resultdata = res.result.records || res.result || []
            this.erpPackageFeedingDetailTable.dataSource = resultdata.map((item) => ({
              materialCode: item.packageCode,
              materialName: item.packageName,
              materialSpec: item.noneSpec,
              meUnit: item.meUnit,
              //   meNum: item.mainQuantity,
              auUnit: item.auUnit,
              //   auNum: item.auxiliaryQuantity,
              stockNum: item.stockNum,
            }))
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    getAllTable() {
      let values = this.tableKeys.map((key) => getRefPromise(this, key))
      return Promise.all(values)
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      this.$nextTick(() => {})
      // 加载子表数据
      if (this.model.id) {
        let params = { id: this.model.id }
        this.requestSubTableData(this.url.erpPackageFeedingDetail.list, params, this.erpPackageFeedingDetailTable)
      }
    },
    //校验所有一对一子表表单
    validateSubForm(allValues) {
      return new Promise((resolve, reject) => {
        Promise.all([])
          .then(() => {
            resolve(allValues)
          })
          .catch((e) => {
            if (e.error === VALIDATE_FAILED) {
              // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
              this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
            } else {
              console.error(e)
            }
          })
      })
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        erpPackageFeedingDetailList: allValues.tablesValue[0].tableData,
      }
    },
    validateError(msg) {
      this.$message.error(msg)
    },
    // 点击新增，查询该车间仓库下的物料列表
    handleAddMaterial() {
      // 打开物料列表弹窗，传递计划单号和生产车间
      this.$refs.materialListModal.add({
        ifPackage: true,
        planCode: this.model.planCode,
        orderCode: this.model.orderCode,
        formulaNumber: this.model.formulaNumber,
        workshopCode: this.model.packshopCode
        // workshopCode: this.model.workshopCode
      })
    },
    //保存物料
    selectMaterial(selectedMaterials) {
      // 将选择的物料添加到子表
      if (selectedMaterials && selectedMaterials.length > 0) {
        const newRows = selectedMaterials.map(material => ({
          materialCode: material.materialCode,
          materialName: material.materialName,
          materialSpec: material.specificationModel,
          meUnit: material.unit, 
          meNum: material.quantity, 
          auUnit: material.secondaryUnit, 
          auNum: material.secondaryQuantity, 
          batchNo: material.batchNumber,
          materialBatchNo: material.materialBatchNumber,
          stockNum: material.quantity,
          inventoryId: material.id,
          feedingNum: '' // 投料数量
        }))
        const tableRef = this.$refs[this.refKeys[0]];
        if (tableRef) {
          tableRef.addRows(newRows);
        }
      }
    },
  },
}
</script>

<style scoped></style>
